﻿using System;
using System.Collections;
using Core.Base;
using Global.Mgr;
using UnityEngine;

namespace Core.Mgrs
{
    public class ResMgr : BaseMgr
    {
        /// <summary>
        /// 加载Resources下资源
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="resPath"></param>
        /// <returns></returns>
        public T Load<T>(string resPath) where T : UnityEngine.Object
        {
            var asset = Resources.Load<T>(resPath);
            if (asset == null)
            {
                throw new Exception($"资源路径错误,Path={resPath}");
            }

            return asset;
        }

        /// <summary>
        /// 异步加载Resources下资源
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="resName"></param>
        /// <param name="cb"></param>
        public Coroutine LoadAsync<T>(string resName, Action<T> cb = null) where T : UnityEngine.Object
        {
            return KKGL.MainBehaviour.StartCoroutine(LoadAsync_(resName, cb));
        }

        private IEnumerator LoadAsync_<T>(string resPath, Action<T> cb = null) where T : UnityEngine.Object
        {
            var resHandler = Resources.LoadAsync<T>(resPath);
            yield return resHandler;
            if (resHandler.asset == null)
            {
                throw new Exception($"资源路径错误,Path={resPath}");
            }

            cb?.Invoke(resHandler.asset as T);
        }
    }
}